package ImageHandleModel

import (
	"encoding/base64"
	"encoding/json"
	"io/ioutil"
	"log"
	"myproject/textTranslateModel"
	"myproject/ttsModel"
	"net/http"
)

// 定义接收的JSON结构
type ImageRequest struct {
	Image            string `json:"image"` // Base64编码的图片数据
	SourceLanguage   string `json:"sourceLanguage"`
	TargetLanguage   string `json:"targetLanguage"`
	IsPlayAudioIndex int    `json:"isPlayAudio"`
	AudioVoiceIndex  int    `json:"audioVoice"`
}

// 定义响应的JSON结构
type Response struct {
	Success         bool   `json:"success"`
	RecognizeResult string `json:"recognizeResult"`
	TranslateResult string `json:"translateResult"`
	AudioDataBase64 string `json:"audioDataBase64"`
}

func PhotoTranslateHandler(w http.ResponseWriter, r *http.Request) {
	log.Println("收到拍照翻译请求")
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
	w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
	if r.Method == "OPTIONS" {
		w.WriteHeader(http.StatusOK)
		return
	}

	w.Header().Set("Content-Type", "application/json")

	// 只允许POST方法
	if r.Method != http.MethodPost {
		resp := Response{Success: false, RecognizeResult: "只支持POST方法"}
		err := json.NewEncoder(w).Encode(resp)
		if err != nil {
			return
		}
		return
	}

	// 读取请求体
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		resp := Response{Success: false, RecognizeResult: "读取请求失败"}
		json.NewEncoder(w).Encode(resp)
		log.Printf("读取请求失败: %v", err)
		return
	}
	defer r.Body.Close()

	// 解析JSON
	var req ImageRequest
	err = json.Unmarshal(body, &req)
	if err != nil {
		resp := Response{Success: false, RecognizeResult: "解析请求数据失败"}
		json.NewEncoder(w).Encode(resp)
		log.Printf("解析请求数据失败: %v", err)
		return
	}

	// 检查图片数据
	if req.Image == "" {
		resp := Response{Success: false, RecognizeResult: "图片数据不能为空"}
		json.NewEncoder(w).Encode(resp)
		return
	}

	// 创建保存图片的目录
	//uploadDir := "uploads"
	//err = os.MkdirAll(uploadDir, 0755)
	//if err != nil {
	//	resp := Response{Success: false, Message: "创建目录失败"}
	//	json.NewEncoder(w).Encode(resp)
	//	log.Printf("创建目录失败: %v", err)
	//	return
	//}

	//// 生成文件名（如果未提供）
	//filename := req.Filename
	//if filename == "" {
	//	timestamp := time.Now().UnixNano()
	//	filename = fmt.Sprintf("image_%d.jpg", timestamp)
	//}

	// 解码Base64数据
	//imageData, err := base64.StdEncoding.DecodeString(req.Image)
	//if err != nil {
	//	resp := Response{Success: false, Message: "解码图片数据失败"}
	//	json.NewEncoder(w).Encode(resp)
	//	log.Printf("解码图片数据失败: %v", err)
	//	return
	//}gap: 16px;

	recognizeResult := qwenVlOcr(req.Image)
	translateResult := textTranslateModel.Qwen_mt_plus(recognizeResult, req.SourceLanguage, req.TargetLanguage)

	AudioData := ""
	if req.IsPlayAudioIndex == 0 {
		audioData := ttsModel.SpeechSynthesis(translateResult, req.TargetLanguage, req.AudioVoiceIndex)
		AudioData = base64.StdEncoding.EncodeToString(audioData)
	}
	//// 保存图片到文件
	//filePath := filepath.Join(uploadDir, filename)
	//err = ioutil.WriteFile(filePath, imageData, 0644)
	//if err != nil {
	//	resp := Response{Success: false, Message: "保存图片失败"}
	//	json.NewEncoder(w).Encode(resp)
	//	log.Printf("保存图片失败: %v", err)
	//	return
	//}

	// 返回成功响应
	resp := Response{
		Success:         true,
		RecognizeResult: recognizeResult,
		TranslateResult: translateResult,
		AudioDataBase64: AudioData,
	}
	err = json.NewEncoder(w).Encode(resp)
	if err != nil {
		return
	}
}
